using System;
using System.Collections;
using System.Html;
using System.Runtime.CompilerServices;
using Awaiter;
using Nsb;
using Nsb.Classes;
using ThemeChain;
using WhirliGig.Classes;
using jQueryApi;

namespace PlaySpace.Classes
{
    public delegate bool ValidatorDelegate(string txt);

    [IgnoreNamespace]
    public static class GigForms
    {
        public const string KeysKey = "kk";
        public const string IsPwKey = "ip";
        public const string ValidateException = "ValidateException";

        private static readonly string[] CloneProps =
            new string[]
                {
                    "font-family", "font-color", "font-size",
                    "padding-left", "padding-right", "padding-top", "padding-bottom",
                    "width", "height",
                    "color", "background-color",
                    "border-top-left-radius", "border-top-right-radius", "border-bottom-left-radius", "border-bottom-right-radius"
                };

        [AlternateSignature]
        public static extern string Validate(jQueryObject el);

        public static string Validate(jQueryObject el, ValidatorDelegate fn)
        {
            string v = el.Plugin<Jewl>().GetFValueString();
            //if ((bool) el.GetDataValue(IsPwKey))
            //    v = (string) el.GetDataValue(KeysKey);
            string t = el.GetAttribute("title");
            if (String.IsNullOrEmpty(v) /*|| IsDeef(el)*/)
            {
                Ask.Ok(String.Format("Please provide a value for \"{0}\"", Script.Value(t, el.GetAttribute("id"), "unknown")));
                return null;
            }
            if (fn != null)
            {
                if (!fn(v))
                {
                    return null;
                }
            }
            return v;
        }

        [AlternateSignature]
        public static extern string ValidateThrow(jQueryObject el);

        public static string ValidateThrow(jQueryObject el, ValidatorDelegate fn)
        {
            string v = Validate(el, fn);
            if (v == null)
                throw new Exception(ValidateException);
            return v;
        }

        public static bool NotEmpty(string txt)
        {
            return !String.IsNullOrEmpty(txt);
        }

        public static void SendTheMail(Dictionary mail, bool confirm)
        {
            if ((bool) Storage.GetLocal("DevNoEmail"))
                return;
            Await awx = new Await()
                .AddAw(CloudMail.SendMailAw, mail)
                ;
            if (confirm)
                awx
                    .AddDx(delegate { Ask.Ok("Your request has been received.<br><br>&nbsp;&nbsp;&nbsp;&nbsp;Thank you!"); })
                    ;
            awx.Commit();
        }

        public static void InitializePageInput()
        {
            if (ThemeYoshi.Publishing || ((bool) Storage.GetLocal(ThemeYoshi.CuratingKey) && !ThemeYoshi.CurrentPage.Admin))
                return;

            jQueryObject gigs = jQuery.Select("#PageGigs");

            jQuery.Select("input[type=text],textarea", gigs)
                .Each(
                    delegate(int i, Element domEl)
                    {
                        jQueryObject ths = jQuery.FromElement(domEl);
                        if (ths.GetValue().ToLowerCase().IndexOf("password") != -1)
                        {
                            // Convert input type to password
                            string id = ths.GetAttribute("id");
                            jQueryObject newpw = jQuery.FromHtml("<input type='password'/>")
                                .InsertBefore(ths);
                            newpw.AddClass(ths.GetAttribute("className"));
                            newpw.Attribute("title", ths.GetValue());
                            newpw.Value("");
                            Css.Clone(ths, newpw);
                            ths.RemoveAttr("id");
                            newpw.Attribute("id", id);
                            LabelBehind(newpw, ths);
                            ths = newpw;
                        }
                        else
                        {
                            ths.Attribute("title", ths.GetValue());
                            ths.Value("");
                            LabelBehind(ths);
                        }
                        ths.AddClass("UserInput");
                        ths.Keydown(
                            // Do default button on return key
                            delegate(jQueryEvent e)
                            {
                                if (e.Which == 13)
                                {
                                    jQuery.Select(".DefaultButton").First().Click();
                                    DomElement.CancelEvent(e);
                                }
                            });
                    }
                )
                ;
        }

        public static void SetDeef(jQueryObject el)
        {
            el.Value("").Trigger("myInit");
        }

        [AlternateSignature]
        public static extern void LabelBehind(jQueryObject el);

        public static void LabelBehind(jQueryObject el, jQueryObject use)
        {
            if (ThemeYoshi.Publishing)
                return;

            string c1 = Css.Fade(el.GetCSS("color"), .40);
            string c2 = Css.Fade(el.GetCSS("color"), .75);

            jQueryObject label = use;

            if (use == null)
            {
                label = jQuery.FromHtml("<input type='text'/>");
                Css.Clone(el, label /*, CloneProps*/);
            }

            label
                .InsertBefore(el)
                .AddClass("LblBhd")
                .Value(el.GetAttribute("title"))
                .CSS("position", "absolute")
                .RemoveAttr("tabindex")
                .FocusIn(
                    delegate(jQueryEvent e)
                    {
                        el.Plugin<Jewl>().ReFocus();
                        DomElement.CancelEvent(e);
                    })
                ;
            if (!jQuery.Browser.MSIE)
                label.Attribute("disabled", "disabled");

            el
                .Bind("myInit focusout", delegate(jQueryEvent e) { ToggleLabel(e, c1); })
                .Bind("focusin keydown paste input", delegate(jQueryEvent e) { ToggleLabel(e, c2); })
                .Data("bgcolor", el.GetCSS("background-color"))
                ;

            el.CSS(new Dictionary("background-color", "transparent"));
            Pos p = (Pos) (object) el.Position();
            label.CSS(new Dictionary("color", c1, "top", p.Top, "left", p.Left, "margin", 0, "z-index", -1));

            el.Trigger("myInit");
        }

        public static void ToggleLabel(jQueryEvent e, string color)
        {
            jQueryObject input = jQuery.FromElement(e.Target);
            Window.SetTimeout(
                delegate
                {
                    string v = input.GetValue();
                    if (String.IsNullOrEmpty(v))
                    {
                        input.CSS("background-color", "transparent");
                        input.Prev(".LblBhd").CSS("color", color).Show();
                    }
                    else
                    {
                        input.CSS("background-color", (string)input.GetDataValue("bgcolor"));
                        input.Prev(".LblBhd").Hide();
                    }
                }, 0);
        }
    }
}